import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';

const logger = new Logger('FileController');

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    if (exception instanceof HttpException) {
      return handleHttpException(exception, host);
    }

    if (exception instanceof Error) {
      logger.log(`Got Error: ${exception.message}, ${exception.stack}`);
      const ctx = host.switchToHttp();
      const response = ctx.getResponse();

      const status =
        exception instanceof HttpException
          ? exception.getStatus()
          : HttpStatus.INTERNAL_SERVER_ERROR;

      response.status(status).json({
        code: 500,
        message: 'Internal server error',
        timestamp: new Date().toISOString(),
        stack: `${exception.message}: ${exception.stack}`,
      });
    }
  }
}

function handleHttpException(exception: HttpException, host: ArgumentsHost) {
  logger.log(`Got http error: ${exception.message}, ${exception.stack}`);

  const ctx = host.switchToHttp();
  const response = ctx.getResponse();
  const status = exception.getStatus();

  if (
    exception.getResponse() instanceof Object &&
    (exception.getResponse() as any).error
  ) {
    response.status(HttpStatus.OK).json({
      timestamp: new Date().toISOString(),
      code: status,
      message: (exception.getResponse() as any).error,
    });
    return;
  }
  // //自定义返回对象 //业务状态码
  if (exception.getResponse() instanceof Object) {
    response.status(HttpStatus.OK).json({
      ...(exception.getResponse() as Object),
      timestamp: new Date().toISOString(),
    });

    return;
  }

  // 这个状态码只能是http的值
  response.status(HttpStatus.OK).json({
    code: status,
    message: exception.message,
    timestamp: new Date().toISOString(),
  });
}
